package com.probox.modules.controller.wechat;

import com.alibaba.fastjson.JSONObject;
import com.probox.common.core.web.controller.BaseController;
import com.probox.common.core.web.domain.AjaxResult;
import com.probox.common.entity.domain.wechat.EnterpriseInfo;
import com.probox.common.entity.mapper.wechat.WechatAuthorizationInfoMapper;
import com.probox.common.entity.service.wechat.WechatMiniService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 快速注册小程序
 *
 * @author usoft
 * @date 2021-05-28
 */
@RestController
@RequestMapping("/wechat/applet")
public class WechatAuthorizationController extends BaseController {

    @Autowired
    private WechatMiniService wechatMiniService;

    @Autowired
    private WechatAuthorizationInfoMapper wechatAuthorizationInfoMapper;

    /**
     * 创建小程序
     * @EnterpriseInfo 企业信息类
     */
    @PostMapping("/register/applet")
    public String registerApplet(@RequestBody EnterpriseInfo enterpriseInfo){
        logger.info("开始创建小程序请求参数=>"+enterpriseInfo);
        String rst = wechatMiniService.registerApplet(enterpriseInfo);
        logger.info("创建小程序返回值=>"+rst);
        return rst;
    }


    /**
     * 查询创建任务状态
     * @EnterpriseInfo 企业信息类
     */
    @PostMapping("/register/findCreateTask")
    public String findCreateTask(@RequestBody(required = false) EnterpriseInfo enterpriseInfo){
        logger.info("查询创建任务状态....");
        String createTask = wechatMiniService.findCreateTask(enterpriseInfo);
        logger.info("创建任务状态=>"+createTask);
        return createTask;
    }


    /**
     * 复用公众号主体注册小程序(跳转授权页)
     */
    @RequestMapping(method = {RequestMethod.GET,RequestMethod.POST},value = "/fastregisterauth")
    public AjaxResult ToAuthorization(@RequestBody String AuthorizationJson)throws IOException{
        JSONObject jsonObject = JSONObject.parseObject(AuthorizationJson);
        String indexUrl =  jsonObject.getString("indexUrl");
        String authorizationInfo =  jsonObject.getString("authorizationInfo");
        logger.info("开始跳转到微信公众平台授权页面,返回index:{},authorizationInfo:{}",indexUrl,authorizationInfo);
        String url = wechatMiniService.ToAuthorization(indexUrl,authorizationInfo);
        logger.info("返回url=>"+url);
        Map<String,String> map = new HashMap<>();
        map.put("AuthorizationUrl",url);
        return AjaxResult.success(map);
    }

    /**
     * 跳转回首页
     */
    @RequestMapping(method = {RequestMethod.GET,RequestMethod.POST},value = "/skipIndex")
    public void skipIndex(HttpServletRequest request,HttpServletResponse resp) throws IOException {
        logger.info("跳转回第三方平台....");
        String ticket = request.getParameter("ticket");
        String authorizationToken = request.getParameter("authorizationToken");
        String allworkAppid = request.getParameter("allworkAppid");
        String bindRefreshToken = request.getParameter("bindRefreshToken");
        String platformid = request.getParameter("platformid");
        logger.info("skipIndex  ticket:"+ticket);
        logger.info("skipIndex  authorizationToken:"+authorizationToken);
        logger.info("skipIndex  appid:"+allworkAppid);
        logger.info("skipIndex  bindRefreshToken:"+bindRefreshToken);
        //复用公众号主题注册小程序(跳转第三方平台,快速注册)
        logger.info("开始注册....");
        String rst = wechatMiniService.speedinessRegiter(ticket,authorizationToken,platformid,allworkAppid,bindRefreshToken);
        logger.info("注册返回参数=>"+rst);
        //跳转回授权页
        String url = request.getParameter("url");
        logger.info("注册成功跳转url:"+url);
        if("0".equals(rst)){
//            QueryWrapper<WechatAuthorizationInfo> authorizationInfoQueryWrapper = new QueryWrapper<>();
//            authorizationInfoQueryWrapper.eq("PLATFORM_ID", platformid);
//            authorizationInfoQueryWrapper.eq("AUTHORIZER_TYPE","allwork");
//            WechatAuthorizationInfo wechatAuthorizationInfo = wechatAuthorizationInfoMapper.selectOne(authorizationInfoQueryWrapper);
            resp.sendRedirect(url);
        }else{
            url = "https://console.yooruan.com/register/data";
            resp.sendRedirect(url+"?error="+ URLEncoder.encode(rst,"UTF-8"));
        }
    }

    /**
     * 判断当前平台是否绑定小程序或公众号
     */
    @GetMapping("/isBindThirdParty/{authorizationType}")
    public HashMap isBind(@PathVariable("authorizationType") String authorizationType){
        HashMap rst =  wechatMiniService.isBind(authorizationType);
        return rst;
    }

    /**
     * 跳转换绑管理员页面
     */
    @RequestMapping(method = {RequestMethod.GET,RequestMethod.POST},value = "/IntieAdmin")
    public AjaxResult IntieAdmin(@RequestBody String AuthorizationJson)throws IOException{
        JSONObject jsonObject = JSONObject.parseObject(AuthorizationJson);
        String indexUrl =  jsonObject.getString("indexUrl");
        String authorizationType =  jsonObject.getString("authorizationType");
        logger.info("开始跳转到微信公众平台授权页面,返回index:{},authorizationType:{}",indexUrl,authorizationType);
        String url = wechatMiniService.IntieAdmin(indexUrl,authorizationType);
        logger.info("返回url=>"+url);
        Map<String,String> map = new HashMap<>();
        map.put("IntieUrl",url);
        return AjaxResult.success(map);
    }

    /**
     * 换绑小程序管理员接口
     */
    @RequestMapping(method = {RequestMethod.GET,RequestMethod.POST},value = "/skipIntie")
    public void skipIntie(HttpServletRequest request,HttpServletResponse resp) throws IOException {
        logger.info("跳转至第三方平台,快速注册完成管理员换绑....");
        String taskid = request.getParameter("taskid");
        String bindAllworkAppid = request.getParameter("bindAllworkAppid");
        String bindRefreshToken = request.getParameter("bindRefreshToken");
        String appid = request.getParameter("appid");
        logger.info("skipIndex  taskid:"+taskid);
        logger.info("skipIndex  bindAllworkAppid:"+bindAllworkAppid);
        logger.info("skipIndex  bindRefreshToken:"+bindRefreshToken);
        logger.info("skipIndex  appid:"+appid);
        String rst = wechatMiniService.IntieRegiter(taskid,bindAllworkAppid,bindRefreshToken,appid);
        String url = request.getParameter("url");
        if("0".equals(rst)){
            resp.sendRedirect(url);
        }else{
            resp.sendRedirect(url+"?error="+ URLEncoder.encode("换绑管理员错误","UTF-8"));
        }
    }


}
